package com.xxx.springboot.util.encrypt;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;


/**
 * AES加密
 */
public class AESUtil {

    // 加密
    public static byte[] encrypt(byte[] content, byte[] keyBytes) throws Exception {
        SecretKeySpec key = new SecretKeySpec(keyBytes, "AES");
        Cipher cipher = Cipher.getInstance("AES");
        cipher.init(Cipher.ENCRYPT_MODE, key);
        return cipher.doFinal(content);
    }

    // 解密
    public static byte[] decrypt(byte[] content, byte[] keyBytes) throws Exception {
        SecretKeySpec key = new SecretKeySpec(keyBytes, "AES");
        Cipher cipher = Cipher.getInstance("AES");
        cipher.init(Cipher.DECRYPT_MODE, key);
        return cipher.doFinal(content);
    }

    public static void main(String[] args) throws Exception {
        //加密
        byte[] key = "1234567890123456".getBytes();  // 密钥需要为16位字节
        String content = "Hello, World!";  // 加密内容
        byte[] resultEn = AESUtil.encrypt(content.getBytes(), key);//加密
        String byte2Base64 = Base64.getEncoder().encodeToString(resultEn);  // 转为base64格式
        System.out.println(byte2Base64); //加密后的base64字符串

        //注意跟加密必须使用同一key
        //解密
        byte[] base642Byte = Base64.getDecoder().decode(byte2Base64); //将base64加密后的结果base64解码
        byte[] resultDe = AESUtil.decrypt(base642Byte, key); //解密
        System.out.println(new String(resultDe));
    }

}
